package com.zyz.sunliky;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.taobao.api.ApiException;

public class test {


    public String appkey;

    public String appsecret;

    public static void main(String[] args) {
        test testInstance = new test();
       // String unionid = dingDingUtil.getUnionid(dinguserid);
        //String dinguserid = "085769595724119246";
        //String dinguserid = "16347094151792744";
        String dinguserid = "025008302114989282";
        String unionid = testInstance.getUnionid(dinguserid);
    }
    //得到用户详细信息
    public String getUnionid(String userid) {
        try {
            String access_token = getdingdingtoken();
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userid);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = client.execute(req, access_token);
            OapiV2UserGetResponse.UserGetResponse result = rsp.getResult();
            if (0==rsp.getErrcode()){
                String unionid = result.getUnionid();
                System.out.println(unionid);
                return unionid;
            }
            return null;
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
    }


    public String getdingdingtoken() {
        HttpRequest get = HttpUtil.createGet("https://oapi.dingtalk.com/gettoken?appkey=" + "dingiqut9kfzjburqy2x" + "&appsecret=" + "Mu4NYqD8cIPWVGMlUJsF0UdIVlT6WcWErvIqo2QktR7P3mQfHwHX5ZyBSta5mRHl");
        String body = get.execute().body();
        if (!StringUtils.isEmpty(body)) {
            JSONObject object = JSON.parseObject(body);
            if (object.getInteger("errcode") == 0) {
                return object.getString("access_token");
            }
            return null;
        }
        return null;
    }


}
